{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Python Data Types" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Comments\n", "Comments can be made by inserting a **\\#** before your string. In addition we can create a **Docstring**, which is any text encapsulated by **\"\"\"**." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "#This is a single line comment, it is denoted by a single hash/pound sign\n", "\"\"\"This is a multine line comment or Docstring\n", "Docstrings, unlike # comments, are evaluated (more on this later!)\n", "\"\"\"" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Strings\n", "Strings are imutable in python, meaning that they can't be changed. They can be defined by a **\\'** or a **\\\"**. Pep8, python's defacto styling recommneds picking with a style and sticking to it (I'm not the best at that)." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "#Strings\n", "\n", "print(\"**********\\nStrings:\")\n", "hello = \"hello\"\n", "world = \"world\" # We can also comment after any line of code\n", "single_quotes = 'string with single quotes' # Strings can be defined with ' or \"\n", "# We can print out any string to the console using the print() function\n", "print(hello)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Concatenation\n", "We can easily mesh strings together simply by adding them together." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "print(\"**********\\nString Concatenation:\")\n", "hw2 = hello + \" \" + world # Strings can be joined with a simple +\n", "print (hw2)\n", "hw3 = hello + \" \" + world + 3 # But we can't concatenate other types - this raises an error\n", "print(hw3)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Indexing/Slicing\n", "We can also index into a string (i.e. select certain portions of the string) by using a set notation:\n", "\n", "**Indexing Rules:**\n", " - [x:y:z] gets from the x element to the yth element by z elements\n", " - ex. [2:5:2] will get the 2nd and 4th element (2, skip 3, 4, end) \n", " - [-x] gets the xth element working from the end of the string\n", " - ex. long_str[-2] would return n\n", " " ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "print(\"**********\\nString Indexing:\")\n", "long_str = \"This is an example of a long string\"\n", "print(long_str[2]) # We can index into a string using brackets\n", "print(long_str[5:]) # [n:] will print out fourth element onward\n" ] }, { "cell_type": "markdown", "metadata": { "collapsed": true }, "source": [ "### In class work" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "\n", "#Problem 1\n", "\"\"\"\n", "Using indexing and concatentaiton, print out \"Hello world\" from the provided string (hw)\n", "\"\"\"\n", "hw = \"Hello there are a couple of words here that make the world far apart\"\n", "\n", "\n", "#Problem 2\n", "\"\"\"\n", "There is a hidden message in the text below\n", " - hint: you'll only want every other letter!\n", "\"\"\"\n", "encoded_str = \"ydouuf bwberrmep daebklqep ptgot vpdamrgshev itghfipsq itxehxutk!q\"\n", "\n", "\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Ints\n", "Integers have a fairly standard behavior" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Ints\n", "print(\"**********\\nInts:\")\n", "a = 6 # You may have noticed, but in python you do not need to define the type of the variable\n", "# Python is dynamically typed, but is also strongly typed\n", "# This means I don't need to define the type when declaring variables, but any type conversion must be explicit\n", "b = 5\n", "c = a + b # All regular mathematic symbols work as expected in python (+, -, *, /, % - modulo)\n", "print(a, \"plus\", b, \"=\", c) # You can print out any list of objects" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Formatting Strings\n", "There are a number of ways to format strings in python:\n", " - Simple concatenation, as shown earlier\n", " - Ex: str(4) + ' the number four'\n", " - Formatting strings\n", " - Ex: \"{} the number four\".format(4)\n", " - f-strings\n", " - Ex: f'{4} the number four'\n", " \n", "Currently f-strings are the recommended format method." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "print(\"**********\\nFormatting outputs:\")\n", "output = \"{0} plus {1} = {2}\"\n", "print(output.format(a, b, c)) # More sophisticated outputs can be formatted using the .format() method\n", "print(output.format(a+c, b, a+c+b))\n", "\n", "# f-Strings - a new features since python 3.6 enable us to do inline formatting\n", "print(f'{a+c} plus {b} = {a+b+c}')\n", "\n", "\"\"\" {str}.format() is a method for string objects (does everyone know what an objects and methods are?)\n", "More info on string formatting options - https://realpython.com/python-string-formatting/\n", "\"\"\"" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "print(\"**********\\nAssignment Operations:\")\n", "c = 11\n", "c += 1 # In python you can use assignment operators for all of the basic mathematical opeartions\n", "# Rather than c = c + 1\n", "print(c) # c will now equal 12\n", "c *= 3\n", "print(c) # c will now be 36 (12*3)" ] }, { "cell_type": "markdown", "metadata": { "collapsed": true }, "source": [ "### In class work" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "#Problem 1\n", "\"\"\"\n", "Make a prediction (in comment form) on the output of the two equations.\n", "Then use an f-String to print out their results and check your prediction.\n", "\"\"\"\n", "eq1 = 3 + 2 * 4\n", "eq2 = (3 + 2) * 4\n", "\n", "\n", "#Problem 2\n", "\"\"\"\n", "Divide two numbers that are not divisible (i.e. tleave a remainder).\n", "What does the outcome tell you about how python handles integer division?\n", "\"\"\"\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Floats\n", "In python real numbers are desingated by the float() type (or at least in most cases)." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "#Floats\n", "print(\"**********\\nFloats:\")\n", "a = 6\n", "d = 2.0 # by adding the decimal we change the type of the object created\n", "print(f\"a is type {type(a)}, d is type{type(d)}\") # We can see the type of an object with the type() function\n", "print(f\"a/d = {a/d} and is type {type(a/d)}\") # An int, float operation will result in a float\n", "\n", "print(\"**********\\nLeaving Remainders:\")\n", "print(type(3/4)) # Any division leaving a remainder will also result in a float\n", "\n", "print(\"**********\\nType Conversion:\")\n", "e = int(a/d) # We can convert to a int/float using int()/float()\n", "print(f\"e = {e}, and is type {type(e)}\")\n", "\n", "# NOTE - comparing floats can be tricky due to what tolerance level you care about\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Booleans and None type" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "\n", "# Python has True and False boolean values\n", "print(\"**********\\nBools:\")\n", "print(type(True))\n", "\n", "# None, [], 0, False, list(), {} are treated as false in control flow operations\n", "print(bool(0))\n", "\n", "\n", "# Note - None (of NoneType) is typically used to express no value" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Comparison Operators/Equalities" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "\n", "# Python uses the standard bool operations >, <, <=, >=, ==, !=\n", "print(1>0) # Should be True\n", "print(1<0) # Should be False\n", "\n", "print(\"hello\" == \"hello\") # Should be True\n", "print(\"Hello\" == \"hello\") # Should be False, string comparisoin is type sensitive\n", "print(\"5\" == 5) # Should be False, python won't convert types" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Logical Operators" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "\n", "# Python uses 'and', 'or', and 'in' for logical operations\n", "x = 5\n", "print(x > 0 and x < 10) #Should be True\n", "print(x < 10 or x == 5) #Should be True\n", "print(not True) #Should be false\n", "\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Boolean 'in' statement\n", "\n", "# Python you can check for inclusion using the 'in' statement\n", "lst = [3,6,8,34]\n", "print(3 in lst) # x in y checks if x is a value within the iterator (lst in this case)\n", "\n", "print(\"hello\" in \"hello world\")\n", "print(\"x\" in \"hello world\")\n", "\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Lists\n", "Think arrays!" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "print(\"**********\\nLists:\")\n", "a = [4,2,3,1] # lists are literally lists of objects\n", "print(a)\n", "b = [\"hello\", 2, 3.0] # Unlike arrays lists are not limited to one type of object\n", "print(b)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Modifying Lists\n", "Many python list operations end up modifying the objects in memory, so be careful when using assignments!" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "print(\"**********\\nModifying Lists:\")\n", "b.extend(a) # We can extend a list by elements in another list\n", "print(b)\n", "b.append(7) #Or we can append singlular values\n", "b.append([8]) #Be careful when you are using extend vs append!\n", "print(b)\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "print(\"**********\\nSumming and Sorting:\")\n", "print(sum(a)) # There are even some very useful list based methods\n", "a.sort(reverse = True)\n", "print(a)\n", "\n", "sum(b) # But you need to be careful that the operation can iterate over all of the elements in the list" ] }, { "cell_type": "markdown", "metadata": { "collapsed": true }, "source": [ "### In class work" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Problem 1\n", "\"\"\"\n", "What happens when we sum ints and floats?\n", "\"\"\"\n", "\n", "# Problem 2\n", "\"\"\"\n", "What happens if we set a value equal to a sorted list (e.g. test = a.sort()),\n", "can anyone explain why this happens?\n", "\"\"\"" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Dictionaries\n", "Think Hashmaps!" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "print(\"**********\\nDictionaries:\")\n", "a = {'one': 1, 'two': 2} #Dictionaries are key-value based and instantiaed with {} or dict()\n", "print(a['one']) #You can access values based on their index\n", "\n", "print(\"**********\\nDict Methods:\")\n", "print(a.keys()) #You can access features of the dict through a variety of different methods\n", "print(a.values())\n", "\n", "print(\"**********\\nHandling Unknown Elements:\")\n", "print(a.get('three')) #dict.get() is a safe method to check if an element exists (We'll cover the None type momentarily)\n", "a['three'] #this will raise an error\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### In class work" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "\n", "\"\"\"\n", "How are these two objects different?\n", "\"\"\"\n", "obj1 = [1,2,3,4]\n", "obj2 = {0:1, 1:2, 2:3, 3:4}\n", "\n", "\"\"\"\n", "What do you think are some of the advantages of Dicts?\n", "When do you think you would use a Dict vs a List?\n", "\"\"\"\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.6.6" } }, "nbformat": 4, "nbformat_minor": 2 }